package com.meb.imageexif;


import android.location.Location;
import android.text.TextUtils;

import androidx.exifinterface.media.ExifInterface;

import com.amap.api.maps2d.model.LatLng;

import java.io.IOException;

public class ImageUtils {
    public static LatLng getPhotoLocation(String imagePath) {
        float output1 = 0;
        float output2 = 0;

        try {
            ExifInterface exifInterface = new ExifInterface(imagePath);
            String latValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
            String lngValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
            String latRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
            String lngRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
            if (latValue != null  && lngValue != null) {
                output1 = convertRationalLatLonToFloat(latValue, latRef);
                output2 = convertRationalLatLonToFloat(lngValue, lngRef);
            }
//            setDiffColor(phoneTV, "手机型号：" + deviceName + "," + deviceModel);
//            setDiffColor(latlngTV, "经纬度：" + output1 + ";" + output2);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new LatLng(output1, output2);
    }

    public static float convertRationalLatLonToFloat(
            String rationalString, String ref) {

        String[] parts = rationalString.split(",");

        String[] pair;
        pair = parts[0].split("/");
        double degrees = Double.parseDouble(pair[0].trim())
                / Double.parseDouble(pair[1].trim());

        pair = parts[1].split("/");
        double minutes = Double.parseDouble(pair[0].trim())
                / Double.parseDouble(pair[1].trim());

        pair = parts[2].split("/");
        double seconds = Double.parseDouble(pair[0].trim())
                / Double.parseDouble(pair[1].trim());

        double result = degrees + (minutes / 60.0) + (seconds / 3600.0);
        if (!TextUtils.isEmpty(ref)){
            if ((ref.equals("S") || ref.equals("W"))) {
                return (float) -result;
            }
        }

        return (float) result;
    }

    //经纬度转度分秒
    public static String convertToDegree(double gpsInfo) {
        String dms = Location.convert(gpsInfo, Location.FORMAT_SECONDS);
        return dms;
    }

    //度分秒转经纬度
    public static Double convertToCoordinate(String stringDMS) {
        if (stringDMS == null) return null;
        String[] split = stringDMS.split(":", 3);
        return Double.parseDouble(split[0]) + Double.parseDouble(split[1]) / 60 + Double.parseDouble(split[2]) / 3600;
    }
}
